package com.imooc.netty.websocket;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketClientProtocolHandler;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.stream.ChunkedWriteHandler;

/**
 * @author 朝花不迟暮
 * @version 1.0
 * @date 2020/12/28 22:37
 */
public class WSServerInitializer extends ChannelInitializer<SocketChannel>
{

    @Override
    protected void initChannel(SocketChannel ch) throws Exception
    {
        ChannelPipeline pipeline = ch.pipeline();
        //ws基于http协议，所以要有编解码器
        pipeline.addLast(new HttpServerCodec());
        //对写入大数据流的支持
        pipeline.addLast(new ChunkedWriteHandler());
        //在netty中,几乎都会使用到这个handler
        pipeline.addLast(new HttpObjectAggregator(1024 * 64));
        //服务器处理的协议,用户给客户端连接访问的路由
        pipeline.addLast(new WebSocketServerProtocolHandler("/ws"));
        // 自定义的handler
        pipeline.addLast(new ChatHandler());
    }
}
